import requests
import datetime
import time
import json
import os
import logging
import pandas as pd
import threading
from socket import *

# config读取
config = json.loads(open(r'config.json', encoding='utf-8').read())

tomcats = config["tomcats"]
restartWeek = config["restartWeek"]
restartTime = config["restartTime"]

isRestart = True

# 创建一个logger
logger = logging.getLogger('listen')
logger.setLevel(logging.DEBUG)

# 创建一个handler，用于写入日志文件
fh = logging.FileHandler('restart.log')
fh.setLevel(logging.DEBUG)

# 定义handler的输出格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)

# 给logger添加handler
logger.addHandler(fh)


# 根据端口干掉
def kill_port(port):
    find_port = 'netstat -aon | findstr 0.0.0.0:%s | findstr LISTENING' % port
    result = os.popen(find_port)
    info = result.read().split('\n')
    data = []
    for line in info:
        if not line:
            continue
        temp = [str for str in line.split(" ") if str]
        data.append(temp)
    parser_cmd(data)


# 干掉他！！！
def parser_cmd(data):
    columns = ["type", "secret", "open", "status", "pid"]
    df = pd.DataFrame(data=data, columns=list(columns))
    for index in range(len(data)):
        pid = df.loc[index, 'pid']
        kill_pid(pid)


# 根据PID干掉
def kill_pid(pid):
    find_kill = 'taskkill -f -pid %s' % pid
    result = os.popen(find_kill)


# 启动tomcat
def startTomcat(path):
    os.chdir(path + "\\bin")
    os.system(".\\startup.bat")


def restart():
    local = time.localtime()
    if (local.tm_wday + 1) in restartWeek:
        hour = str(local.tm_hour) if local.tm_hour > 10 else '0' + str(local.tm_hour)
        minute = str(local.tm_min) if local.tm_min > 10 else '0' + str(local.tm_min)
        global isRestart
        if((hour + ":" + minute) == restartTime) and isRestart:
            isRestart = False
            logger.info("进入服务的重启")
            for item in tomcats:
                kill_port(item["port"])
                time.sleep(2)
                logger.info("重启了服务：" + item["name"])
                startTomcat(item["tomcatPath"])
                time.sleep(2)
        else:
            isRestart = True


# 启动执行开始方法
def restartTimer():
    try:
        do = threading.Thread(target=restart, )
        do.start()
        while do.is_alive():
            time.sleep(0.5)
    except Exception as r:
        logger.error(str(r))
    finally:
        threading.Timer(30, restartTimer, ()).start()


restartTimer()